import { defineStore } from 'pinia'
import { get, post, API_PATHS } from '@/utils/api'

/**
 * 文章接口
 * @description 定义文章的基本信息结构
 */
export interface Article {
    id: string
    title: string
    summary: string
    content: string
    cover: string
    author: string
    category: string
    tags: string[]
    status: 'published' | 'draft' | 'archived'
    createTime: string
    updateTime: string
    publishTime: string
    views: number
    likes: number
    comments: number
    isLiked: boolean
    isBookmarked: boolean
}

/**
 * 分类接口
 * @description 定义文章分类的基本信息
 */
export interface Category {
    id: string
    name: string
    slug: string
    description: string
    articleCount: number
    color: string
}

/**
 * 标签接口
 * @description 定义文章标签的基本信息
 */
export interface Tag {
    id: string
    name: string
    slug: string
    articleCount: number
    color: string
}

/**
 * 分页接口
 * @description 定义分页信息的基本结构
 */
export interface Pagination {
    page: number
    pageSize: number
    total: number
    totalPages: number
}

/**
 * 搜索过滤接口
 * @description 定义文章搜索和过滤的条件
 */
export interface SearchFilters {
    keyword: string
    category: string
    tags: string[]
    status: string
    dateRange: {
        start: string
        end: string
    }
    sortBy: 'createTime' | 'updateTime' | 'views' | 'likes'
    sortOrder: 'asc' | 'desc'
}

/**
 * 文章Store状态类型
 */
interface ArticleState {
    articles: Article[]
    currentArticle: Article | null
    categories: Category[]
    tags: Tag[]
    pagination: Pagination
    filters: SearchFilters
    loading: boolean
    error: string | null
    cache: Map<string, any>
}

/**
 * 文章状态管理Store
 * @description 管理文章相关的所有状态，包括列表、详情、分类、标签等
 */
export const useArticleStore = defineStore('article', {
    state: (): ArticleState => ({
        // 文章列表
        articles: [],

        // 当前文章详情
        currentArticle: null,

        // 分类列表
        categories: [],

        // 标签列表
        tags: [],

        // 分页信息
        pagination: {
            page: 1,
            pageSize: 10,
            total: 0,
            totalPages: 0
        },

        // 搜索过滤条件
        filters: {
            keyword: '',
            category: '',
            tags: [],
            status: '',
            dateRange: {
                start: '',
                end: ''
            },
            sortBy: 'createTime',
            sortOrder: 'desc'
        },

        // 加载状态
        loading: false,

        // 错误信息
        error: null,

        // 缓存状态
        cache: new Map<string, any>()
    }),

    getters: {
        /**
         * 获取文章列表
         * @description 返回当前的文章列表
         * @returns {Article[]} 文章数组
         */
        getArticles: (state: ArticleState): Article[] => state.articles,

        /**
         * 获取当前文章
         * @description 返回当前正在查看的文章详情
         * @returns {Article | null} 当前文章或null
         */
        getCurrentArticle: (state: ArticleState): Article | null => state.currentArticle,

        /**
         * 获取分类列表
         * @description 返回所有文章分类
         * @returns {Category[]} 分类数组
         */
        getCategories: (state: ArticleState): Category[] => state.categories,

        /**
         * 获取标签列表
         * @description 返回所有文章标签
         * @returns {Tag[]} 标签数组
         */
        getTags: (state: ArticleState): Tag[] => state.tags,

        /**
         * 获取分页信息
         * @description 返回当前的分页状态
         * @returns {Pagination} 分页信息对象
         */
        getPagination: (state: ArticleState): Pagination => state.pagination,

        /**
         * 获取过滤条件
         * @description 返回当前的搜索和过滤条件
         * @returns {SearchFilters} 过滤条件对象
         */
        getFilters: (state: ArticleState): SearchFilters => state.filters,

        /**
         * 检查是否有更多页面
         * @description 判断是否还有更多页面可以加载
         * @returns {boolean} 是否有更多页面
         */
        hasMorePages: (state: ArticleState): boolean => state.pagination.page < state.pagination.totalPages,

        /**
         * 获取文章统计
         * @description 返回文章的统计信息
         * @returns {Object} 文章统计对象
         */
        getArticleStats: (state: ArticleState) => ({
            total: state.pagination.total,
            published: state.articles.filter(article => article.status === 'published').length,
            draft: state.articles.filter(article => article.status === 'draft').length,
            archived: state.articles.filter(article => article.status === 'archived').length
        }),

        /**
         * 获取热门文章
         * @description 返回按浏览量排序的热门文章列表
         * @returns {Article[]} 热门文章数组
         */
        getPopularArticles: (state: ArticleState): Article[] => {
            return [...state.articles]
                .filter(article => article.status === 'published')
                .sort((a, b) => b.views - a.views)
                .slice(0, 5)
        },

        /**
         * 获取最新文章
         * @description 返回按创建时间排序的最新文章列表
         * @returns {Article[]} 最新文章数组
         */
        getLatestArticles: (state: ArticleState): Article[] => {
            return [...state.articles]
                .filter(article => article.status === 'published')
                .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime())
                .slice(0, 5)
        }
    },

    actions: {
        /**
         * 获取文章列表
         * @description 从服务器获取文章列表，支持分页和过滤
         * @param {number} page 页码，默认为1
         * @param {Partial<SearchFilters>} filters 过滤条件
         * @returns {Promise<{success: boolean, data?: any, error?: string}>} 获取结果
         */
        async fetchArticles(page: number = 1, filters: Partial<SearchFilters> = {}) {
            try {
                this.loading = true
                this.error = null

                // 合并过滤条件
                const mergedFilters = { ...this.filters, ...filters }

                // 构建查询参数
                const params = new URLSearchParams({
                    page: page.toString(),
                    pageSize: this.pagination.pageSize.toString(),
                    ...mergedFilters.keyword && { keyword: mergedFilters.keyword },
                    ...mergedFilters.category && { category: mergedFilters.category },
                    ...mergedFilters.status && { status: mergedFilters.status },
                    sortBy: mergedFilters.sortBy,
                    sortOrder: mergedFilters.sortOrder
                })

                // 添加标签参数
                if (mergedFilters.tags && mergedFilters.tags.length > 0) {
                    mergedFilters.tags.forEach(tag => params.append('tags', tag))
                }

                const response = await get(`${API_PATHS.ARTICLE.LIST}?${params.toString()}`)

                if (response.success && response.data) {
                    this.articles = response.data.items || response.data
                    this.pagination = {
                        page: response.data.page || page,
                        pageSize: response.data.pageSize || this.pagination.pageSize,
                        total: response.data.total || this.articles.length,
                        totalPages: response.data.totalPages || Math.ceil((response.data.total || this.articles.length) / this.pagination.pageSize)
                    }
                    this.filters = mergedFilters
                    return { success: true, data: response.data }
                } else {
                    // 降级使用模拟数据
                    this.useMockArticles()
                    return { success: false, error: response.error || '获取文章列表失败，使用模拟数据' }
                }
            } catch (error) {
                console.error('获取文章列表失败:', error)
                this.error = '获取文章列表失败'
                // 降级使用模拟数据
                this.useMockArticles()
                return { success: false, error: '获取文章列表失败' }
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取文章详情
         * @description 从服务器获取指定文章的详细信息
         * @param {string} id 文章ID
         * @returns {Promise<{success: boolean, data?: Article, error?: string}>} 获取结果
         */
        async fetchArticleById(id: string) {
            try {
                this.loading = true
                this.error = null

                // 检查缓存
                if (this.cache.has(id)) {
                    this.currentArticle = this.cache.get(id)
                    return { success: true, data: this.currentArticle }
                }

                const response = await get(API_PATHS.ARTICLE.DETAIL(id))

                if (response.success && response.data) {
                    this.currentArticle = response.data
                    this.cache.set(id, response.data)
                    return { success: true, data: response.data }
                } else {
                    // 降级使用模拟数据
                    this.currentArticle = this.getMockArticle(id)
                    return { success: false, error: response.error || '获取文章详情失败，使用模拟数据' }
                }
            } catch (error) {
                console.error('获取文章详情失败:', error)
                this.error = '获取文章详情失败'
                // 降级使用模拟数据
                this.currentArticle = this.getMockArticle(id)
                return { success: false, error: '获取文章详情失败' }
            } finally {
                this.loading = false
            }
        },

        /**
         * 获取分类列表
         * @description 从服务器获取所有文章分类
         */
        async fetchCategories() {
            try {
                const response = await get(API_PATHS.CATEGORY.LIST)

                if (response.success && response.data) {
                    this.categories = response.data
                }
            } catch (error) {
                console.error('获取分类列表失败:', error)
            }
        },

        /**
         * 获取标签列表
         * @description 从服务器获取所有文章标签
         */
        async fetchTags() {
            try {
                const response = await get(API_PATHS.TAG.LIST)

                if (response.success && response.data) {
                    this.tags = response.data
                }
            } catch (error) {
                console.error('获取标签列表失败:', error)
            }
        },

        /**
         * 搜索文章
         * @description 根据关键词搜索文章
         * @param {string} keyword 搜索关键词
         * @returns {Promise<{success: boolean, data?: any, error?: string}>} 搜索结果
         */
        async searchArticles(keyword: string) {
            return await this.fetchArticles(1, { keyword })
        },

        /**
         * 按分类筛选文章
         * @description 根据分类筛选文章列表
         * @param {string} category 分类名称
         * @returns {Promise<{success: boolean, data?: any, error?: string}>} 筛选结果
         */
        async filterByCategory(category: string) {
            return await this.fetchArticles(1, { category })
        },

        /**
         * 按标签筛选文章
         * @description 根据标签筛选文章列表
         * @param {string[]} tags 标签数组
         * @returns {Promise<{success: boolean, data?: any, error?: string}>} 筛选结果
         */
        async filterByTags(tags: string[]) {
            return await this.fetchArticles(1, { tags })
        },

        /**
         * 点赞文章
         * @description 对指定文章进行点赞或取消点赞
         * @param {string} articleId 文章ID
         * @returns {Promise<{success: boolean, error?: string}>} 操作结果
         */
        async likeArticle(articleId: string) {
            try {
                const response = await post(API_PATHS.ARTICLE.LIKE(articleId))

                if (response.success) {
                    // 更新文章点赞状态
                    const article = this.articles.find(a => a.id === articleId)
                    if (article) {
                        article.isLiked = !article.isLiked
                        article.likes += article.isLiked ? 1 : -1
                    }

                    // 更新当前文章
                    if (this.currentArticle?.id === articleId) {
                        this.currentArticle.isLiked = !this.currentArticle.isLiked
                        this.currentArticle.likes += this.currentArticle.isLiked ? 1 : -1
                    }

                    return { success: true }
                } else {
                    return { success: false, error: response.error || '点赞失败' }
                }
            } catch (error) {
                console.error('点赞失败:', error)
                return { success: false, error: '点赞失败' }
            }
        },

        /**
         * 收藏文章
         * @description 对指定文章进行收藏或取消收藏
         * @param {string} articleId 文章ID
         * @returns {Promise<{success: boolean, error?: string}>} 操作结果
         */
        async bookmarkArticle(articleId: string) {
            try {
                const response = await post(API_PATHS.ARTICLE.BOOKMARK(articleId))

                if (response.success) {
                    // 更新文章收藏状态
                    const article = this.articles.find(a => a.id === articleId)
                    if (article) {
                        article.isBookmarked = !article.isBookmarked
                    }

                    // 更新当前文章
                    if (this.currentArticle?.id === articleId) {
                        this.currentArticle.isBookmarked = !this.currentArticle.isBookmarked
                    }

                    return { success: true }
                } else {
                    return { success: false, error: response.error || '收藏失败' }
                }
            } catch (error) {
                console.error('收藏失败:', error)
                return { success: false, error: '收藏失败' }
            }
        },

        /**
         * 增加文章浏览量
         * @description 增加指定文章的浏览量
         * @param {string} articleId 文章ID
         */
        async incrementViews(articleId: string) {
            try {
                await post(API_PATHS.ARTICLE.VIEW(articleId))

                // 更新文章浏览量
                const article = this.articles.find(a => a.id === articleId)
                if (article) {
                    article.views += 1
                }

                // 更新当前文章
                if (this.currentArticle?.id === articleId) {
                    this.currentArticle.views += 1
                }
            } catch (error) {
                console.error('增加浏览量失败:', error)
            }
        },

        /**
         * 清除缓存
         * @description 清除所有缓存的文章数据
         */
        clearCache() {
            this.cache.clear()
        },

        /**
         * 清除当前文章
         * @description 清除当前正在查看的文章详情
         */
        clearCurrentArticle() {
            this.currentArticle = null
        },

        /**
         * 重置过滤条件
         * @description 将所有过滤条件重置为默认值
         */
        resetFilters() {
            this.filters = {
                keyword: '',
                category: '',
                tags: [],
                status: '',
                dateRange: {
                    start: '',
                    end: ''
                },
                sortBy: 'createTime',
                sortOrder: 'desc'
            }
        },

        /**
         * 使用模拟文章列表
         * @description 降级时使用的模拟数据
         */
        useMockArticles() {
            this.articles = [
                {
                    id: '1',
                    title: 'Vue 3 Composition API 深入解析',
                    summary: 'Vue 3带来了全新的Composition API,让我们深入了解它的设计理念和使用方法...',
                    content: '# Vue 3 Composition API\n\nVue 3的Composition API是一个革命性的特性...',
                    cover: 'https://picsum.photos/800/400?random=1',
                    author: '管理员',
                    category: '技术',
                    tags: ['Vue3', 'JavaScript', '前端开发'],
                    status: 'published',
                    createTime: '2024-03-15 10:30:00',
                    updateTime: '2024-03-15 10:30:00',
                    publishTime: '2024-03-15 10:30:00',
                    views: 256,
                    likes: 32,
                    comments: 8,
                    isLiked: false,
                    isBookmarked: false
                }
            ]
            this.pagination.total = 1
            this.pagination.totalPages = 1
        },

        /**
         * 获取模拟文章详情
         * @description 降级时使用的模拟文章
         */
        getMockArticle(id: string): Article {
            return {
                id,
                title: 'Vue 3 Composition API 深入解析',
                summary: 'Vue 3带来了全新的Composition API,让我们深入了解它的设计理念和使用方法...',
                content: '# Vue 3 Composition API\n\nVue 3的Composition API是一个革命性的特性...',
                cover: 'https://picsum.photos/800/400?random=1',
                author: '管理员',
                category: '技术',
                tags: ['Vue3', 'JavaScript', '前端开发'],
                status: 'published',
                createTime: '2024-03-15 10:30:00',
                updateTime: '2024-03-15 10:30:00',
                publishTime: '2024-03-15 10:30:00',
                views: 256,
                likes: 32,
                comments: 8,
                isLiked: false,
                isBookmarked: false
            }
        }
    }
})
